/**
 * @author caif
 * @fileoverview context menu viewer
 */
App.Views.contextMenuView = Backbone.View.extend({
    id : 'context-menu',
    
    className: 'context-menu',
    
	initialize : function( options ) {
		var self = this;
	    self.$el.html(Mustache.to_html(tpl.contextMenu , self.model.toJSON()));
	    self.$el.bind('click', function(e) {
         	e.stopPropagation();
        });
        $(document).click(function(e){
        	if(e.which === 1 || e.which === 0){
		    	self.hideMenu();
		    }
		});
		self.appView = options.appView;
		self.docList = self.appView.docList;
		self.docList.delegate('.doc-item', 'click', function(e){
			e.stopPropagation();
			self.hideMenu();
		});
		self.bindEvent();
		self.appView.$el.append(self.$el);
	},
	
	render: function(){
	    return this;
	},
	
	clear: function() {
	    this.model.clear();
	},
	
	hideMenu: function(){
		var self = this;
		self.$el.hide().find('li').hide();
		return self;
	},
	
	removeSelected: function(){
		var self = this;
		self.docList.find(".highlight").removeClass("highlight");
		self.appView.updateHeaderBtn();
		return this;
	},
	
	positionMenu: function(position){
		var self = this,
		menuHeight = self.$el.height(),
        menuWidth = self.$el.width(),
        finalWidth = self.docList.width() + $('#sider').width(),
        finalHeight = self.docList.height() + $('#breadcrumb-bar').height() + $('#document_header').height() + $('#glodon_header').height(),
        top = position.top,
        left = position.left;
        if(top + menuHeight > finalHeight){
        	top -= menuHeight;
        }
        if(left + menuWidth > finalWidth){
        	left -= menuWidth;
        }
        top += 10;
        left += 10;
        self.$el.css({left: left, top: top}).show();
        return self;
	},
	
	contextMenu : function(e){
		var self = this,
		target = e.currentTarget;
		if($(target).is('.doc-item')){
    		if(!$(target).is('.highlight')){
    			self.removeSelected();
			    $(target).find(".inner-item").trigger("click");
    		}
		}
		var contextParam = self.appView.getActionParam();
		self.displayMenu({
            top: e[self.model.get('eventPosY')],
            left: e[self.model.get('eventPosX')]
		}, target, contextParam);
		return false;
	},
	
	displayMenu: function(position, contextEl, contextParam){
		var self = this,
		menu = self.$el;
		self.hideMenu();
		menu.data('currentItem', $(contextEl));
		self.currentSelectedItem = $(contextEl);
		self.currentSelectedItemModel = self.appView.getItemModelById(self.currentSelectedItem.attr('id'));
		if(contextParam.fromProject){
			if(contextParam.inComplete){
                if(contextParam.privileges.canWrite){
                    menu.find('.deleteItem').show();
                }
            }else if($(contextEl).is(self.docList)){
                //has cut items
            	if(contextParam.privileges.canWrite){
                    if(self.canPaste(contextEl, contextParam.isFolder)){
                        menu.find('.pasteItem').show();
                    }else{
                       return false;
                    }
                }
            }else{
                if(contextParam.privileges.canWrite){
                    if(self.canPaste(contextEl, contextParam.isFolder)){
                        menu.find('.pasteItem').show();
                    }
                }
                if(contextParam.privileges.canWrite){
                    menu.find('.cutItem').show();
                }
                if(contextParam.privileges.canDelete){
                    menu.find('.deleteItem').show();
                }
                if(contextParam.multi){
                	if(contextParam.privileges.canRead){
                        menu.find('.pdownloadItem').show();
                    }
                }else{
                	if(contextParam.privileges.canWrite){
                        menu.find('.renameItem').show();
                    }
                    if(contextParam.isFolder){
                        if(contextParam.privileges.canRead){
                            menu.find('.pdownloadItem').show();
                        }
                        if(contextParam.privileges.canWrite && self.appView.canSetPrivilegeByItemId($(contextEl).attr('id'))){
                            menu.find('.privilegeItem').show();
                        }
                    }else{
                    	if(contextParam.privileges.canRead){
                            menu.find('.downloadItem, .detailItem').show();
                        }
                    }
                }
            }
		}else if(contextParam.fromOwnMe){
			if(contextParam.inComplete){
				//upload incomplete item only show delete menu
                menu.find('.deleteItem').show();
			}else if($(contextEl).is(self.docList)){
			    //has cut items
				if(self.canPaste(contextEl, contextParam.isFolder)){
                    menu.find('.pasteItem').show();
				}else{
				   return false;
				}
			}else{
				if(self.canPaste(contextEl, contextParam.isFolder)){
                    menu.find('.pasteItem').show();
                }
			    menu.find('.deleteItem, .cutItem').show();
				if(contextParam.multi){
					menu.find('.pdownloadItem').show();
				}else{
					menu.find('.renameItem, .publicItem').show();
					if(contextParam.isFolder){
						menu.find('.pdownloadItem').show();
					}else{
						menu.find('.downloadItem, .detailItem').show();
					}
					if(contextParam.shared){
						menu.find('.unShareItem').show();
					}
					if(contextParam.published){
						menu.find('.unPublicItem').show();
					}
					menu.find('.shareItem, .publicItem').show();
				}
			}
		}else if(contextParam.fromFilesByMe || contextParam.fromFilesForMe){
			if(contextParam.isFolder || contextParam.multi){
				menu.find('.pdownloadItem').show();
			}else{
				menu.find('.downloadItem').show();
			}
			menu.find('.unShareItem').show();
		}else if(contextParam.fromPublic){
			if(contextParam.isFolder || contextParam.multi){
                menu.find('.pdownloadItem').show();
            }else{
                menu.find('.downloadItem').show();
            }
            menu.find('.unPublicItem').show();
		}else if(contextParam.fromRecycle){
            menu.find('.deleteItem, .recoverItem').show();
        }
        self.positionMenu(position);
	},
    
    bindEvent: function(){
    	var self = this;
    	self.$el.delegate('li', 'click', function(e){
        	var contextParam = self.appView.getActionParam();
			var t = $(this);
			if(t.hasClass('downloadItem')){
				self.downloadItemHandler();
			}else if(t.hasClass('pdownloadItem')){
				self.pdownloadItemHandler();
			}else if(t.hasClass('renameItem')){
				//prevent shortkeys: F2
				if(contextParam.fromProject && !contextParam.privileges.canWrite) return false;
				self.renameItemHandler(e);
			}else if(t.hasClass('shareItem')){
				self.shareItemHandler();
			}else if(t.hasClass('shareInfoItem')){
				self.shareInfoItemHandler();
			}else if(t.hasClass('unShareItem')){
				self.unShareItemHandler();
			}else if(t.hasClass('detailItem')){
				//prevent shortkeys: d
				if(contextParam.fromProject && !contextParam.privileges.canRead) return false;
				self.detailItemHandler();
			}else if(t.hasClass('deleteItem')){
				//prevent shortkeys: delete
				if(contextParam.fromProject && !contextParam.privileges.canDelete) return false;
				self.deleteItemHandler();
			}else if(t.hasClass('recoverItem')){
				self.recoverItemHandler();
			}else if(t.hasClass('cutItem')){
				//prevent shortkeys: ctrl + x
				if(contextParam.fromProject && !contextParam.privileges.canWrite) return false;
                self.cutItemHandler();
            }else if(t.hasClass('pasteItem')){
            	//prevent shortkeys: ctrl + v
            	if(contextParam.fromProject && !contextParam.privileges.canWrite) return false;
                self.pasteItemHandler();
            }else if(t.hasClass('publicItem')){
                self.publicItemHandler();
            }else if(t.hasClass('unPublicItem')){
                self.unPublicItemHandler();
            }else if(t.hasClass('lockItem')){
                self.lockItemHandler();
            }else if(t.hasClass('unLockItem')){
                self.unLockItemHandler();
            }else if(t.hasClass('privilegeItem')){
                self.privilegeItemHandler();
            }
			self.hideMenu();
			e.stopPropagation();
		});
    },
    
    downloadItemHandler: function(){
    	var self = this;
    	window.location.href = App.util.contextPath + "/file/download?id=" + self.getSelectedIds().join(',');
    },
    
    pdownloadItemHandler: function(){
    	var self = this;
		window.location.href = App.util.contextPath + "/file/package?id=" + self.getSelectedIds().join(',');
    },
    
    renameItemHandler: function(e){
    	var self = this,
    	items = self.appView.getActionParam().items;
    	if(items.length !== 1) return;
    	self.appView.getItemModelById(items.attr('id')).trigger('renaming', e);
    },
    
    shareItemHandler: function(){
    	var self = this,
    	model = self.currentSelectedItemModel;
        App.modalHelper.showNormalModal({
            title: 'shareModalTitle',
            url: App.util.contextPath + '/js/widget/share.widget',
            done: function(data, modalBody, okBtn, modal){
            	modalBody.empty().html(Mustache.to_html(data, {
                    title: App.i18n.get('shareModalTitle'),
                    loadContactsTip: App.i18n.get('loadContactsTip'),
                    sharedContactsTip: App.i18n.get('sharedContactsTip'),
                    loadingSharedTip: App.i18n.get('loadingSharedTip')
                }));
                okBtn.text(App.i18n.get('share'));
                modal.addClass('share-modal');
                var errorMsg = modal.find('.error-msg');
                $.get('/account/communicateBook/listContactUser.json', function(data){
                	modal.find('.loading-contacts').remove();
                	var autocompleteSource = [];
                	for(var i = 0, item; i < data.items.length; i++){
                		item = data.items[i];
                		item = (item.displayName === item.accountName) ? item.accountName :  (item.displayName + '<' + item.accountName + '>');
                		autocompleteSource.push({
                			label: item,
                			value: item
                		});
                	}
                	var getAccountByLabel = function(l){
                		if(l.indexOf('<') !== -1){
                			return l.match(/<(.+)>/)[1];
                		}else{
                			return l;
                		}
                	}
                	var checkAccount = function(v){
                	   var isCorrectAccount = App.util.isGlodonAccount(getAccountByLabel(v));
                        if(!isCorrectAccount){
                            errorMsg.text(App.i18n.get('inputRightAccount'));
                            accountName.focus();
                        }
                        return isCorrectAccount;
                	}
            		var tagme = modal.find('.share-container').tagme({
                    	autocomplete: {
                    		source: autocompleteSource,
                    		position: { my : 'left-7 top+5'},
                    		minLength: 0
                    	},
                    	onAdd: function(v){
                    		return checkAccount(v);
                    	}
                    });
                    var accountName = modal.find('.tagme-input').focus(function(){
                    	tagme.addClass('focus');
                    }).blur(function(){
                    	tagme.removeClass('focus');
                    });
                    if(!('placeholder' in document.createElement('input'))){
                    	$('<label class="inp-label username-label">' + App.i18n.get('enterForConfirm') + '</label>').insertBefore(accountName);
                    	accountName.placeholder();
                    }
                    okBtn.click(function(){
                    	var v = accountName.val();
                    	if(v !== ''){
                            if(checkAccount(v)){
                                tagme.tagme('setTags', [v]);
                                accountName.val('');
                            }else{
                                return;
                            }
                        }
                    	var accounts = tagme.tagme('getTags');
                    	if(accounts.length === 0){
                    		errorMsg.text(App.i18n.get('inputAccount'));
                    		return false;
                    	}
                    	var sendAccounts = [];
                    	for (var i = 0; i < accounts.length; i++) {
                    		var acc = getAccountByLabel(accounts[i]);
                    		if(sendAccounts.indexOf(acc) === -1){
                    			sendAccounts.push(acc);
                    		}
                    	}
                    	App.util.showTip(App.i18n.get('isSharing'));
                    	okBtn.addClass('disabled');
            	        $.ajax({
                            data: {
                                fileId : model.get('id'),
                                accountName : sendAccounts.join(',')
                            },
                            type : "post",
                            url : App.util.contextPath + "/share/do.json",
                	        success : function(data){
                	        	App.util.hideTip();
                	        	okBtn.removeClass('disabled');
                	            if(data.failedItems.length > 0){
                	            	errorMsg.text(App.i18n.get('shareFailedWithUserInfo', [data.failedItems.join(', ')]));
                	            	tagme.tagme('clearTags');
                	            	tagme.tagme('setTags', data.failedItems);
                	            }else{
                	            	modal.modal('hide');
                	            }
                	            self.addUserByData(data.successItems, model, modal);
                	            var contextParam = self.appView.getActionParam();
            	            	if(contextParam.fromOwnMe && data.failedItems.length < sendAccounts.length){
            	            		$('<div>', {'class': 'file-shared'}).insertBefore($('.file_lable', self.currentSelectedItem));
            	            		model.set('shared', true);
            	            	}
                	        },
                	        error: function(){
                	        	okBtn.removeClass('disabled');
                	            errorMsg.text(App.i18n.get('shareFailed'));
                	        }
                	    });
                	});
                	$.get('/document/share/shareInfo.json', {
                		fileId: model.get('id')
                	}, function(data){
                		self.addUserByData(data.users, model, modal);
                	});
            	});
            }
        });
    },
    
    addUserByData: function(users, model, modal){
        var self = this;
        function noSharedUserTip(){
            modal.find('.shared-accounts').removeClass('share-accounts-loading').text('该文件' + (model.get('folder') ? '夹' : '') + '暂无共享用户');
        }
        var userCon = modal.find('.shared-user-list'),
        shareListExist = true;
        if(userCon.length < 1){
        	shareListExist = false;
            userCon = $('<ul>', {'class': 'tagme-container shared-user-list'});
        }
        for (var i = 0; i < users.length; i++) {
            var u = users[i];
            userCon.append($('<li>', {title: '点击取消对该用户的共享', text: u.displayName, 'class': 'tagme-item'}).data('userid', u.id).click(function(e){
                var t = $(this);
                $.post('/document/share/undo.json', {
                    fileId: model.get('id'),
                    userId: t.data('userid')
                }, function(){
                    App.util.actionTip('已取消对 "' + t.text() + '" 的共享权限');
                    t.remove();
                    if(userCon.children().length === 0){
                        noSharedUserTip();
                        model.set('shared', false);
                    }
                });
            }));
        }
        if(userCon.children().length === 0){
            noSharedUserTip();
        }else{
            if(shareListExist === false){
                modal.find('.shared-accounts').removeClass('share-accounts-loading').empty().append(userCon);
            }
        }
    },
    
    unShareItemHandler: function(){
    	var self = this;
    	App.util.showTip(App.i18n.get('isUnSharing'));
    	$.ajax({
            data: {
                fileId: self.getSelectedIds().join(',')
            },
            type: "post",
            url: window._global.contextPath + "/share/cancelShare.json", 
	        success: function(){
            	App.util.hideTip();
            	var contextParam = self.appView.getActionParam();
            	if(contextParam.fromOwnMe){
            		self.currentSelectedItemModel.set('shared', false);
            	}else{
					contextParam.items.slideUp(function(){
						$(this).remove();
						self.appView.itemCollection.remove(self.currentSelectedItemModel.get('id'));
					});    	            		
            	}
	        }
	    });
    },
    
    detailItemHandler: function(){
    	var self = this,
    	items = self.appView.getActionParam().items;
    	if(items.length !== 1) return;
    	if(self.docList.hasClass('expand-detail')){
    		self.appView.hideDetailPanel();
    		return;
    	}
        self.appView.showDetailPanel();
        self.currentSelectedItemModel.trigger('update-detail-panel');
    },
    
    deleteItemHandler: function(){
    	var self = this,
    	contextParam = self.appView.getActionParam();
    	if(contextParam.fromRecycle){
            $("#dialog").html(tpl.deleteDialog);
            var allIds = self.getSelectedIds();
            var html = '<p>' + App.i18n.get('deleteItemConfirm') + '</p>';
        	$("#glodon_delete_dlg").find('.text').html(html).end().modal({
                keyboard: true,
                show: true,
                backdrop: "static"
            }).find('.btn-ok').click(function(e){
            	$("#glodon_delete_dlg").modal('hide');
                self.deleteItemsByIds(allIds, contextParam.items, '/recycler/');
        	});
        }else{
        	var allIds = self.getSelectedIds(true);
            self.deleteItemsByIds(allIds.canDeleteIds, allIds.canDeleteEls);
            if(allIds.cannotDeleteIds.length > 0){
            	$("#dialog").html(tpl.deleteDialog);
            	var tip = '';
            	if(allIds.canDeleteIds.length > 0 && allIds.cannotDeleteIds.length > 0 || allIds.cannotDeleteIds.length > 1){
            		tip = App.i18n.get('haveNum', ['<em class="num">' + allIds.cannotDeleteIds.length + '</em>']);
            	}
            	var html = "<p>" + tip + App.i18n.get('deleteFolderNotBlankConfirm') + "</p>";
                $("#glodon_delete_dlg").find('.text').html(html).end().modal('show')
                .find('.btn-ok').click(function(e){
                	$("#glodon_delete_dlg").modal('hide');
                    self.deleteItemsByIds(allIds.cannotDeleteIds, allIds.cannotDeleteEls);
            	});
            }
        }
    },
    
    deleteItemsByIds: function(idsArr, els, url){
    	var self = this;
    	if(idsArr.length < 1) return;
    	App.util.showTip(App.i18n.get('isDeletingTip'));
    	self.appView.hideDetailPanel();
    	$.ajax({
            type : "delete",
            url : window._global.contextPath + (url || "/file/") + idsArr.join(',') +".json",
            success : function(){
            	App.util.hideTip(App.i18n.get('deleteSuccessTip'), 3000);
                _.each(els, function(item, idx){
                	$(item).slideUp(function(){
	                	if(idx === els.length - 1){
	                		var next = $(els[idx]).next();
                			$(this).remove();
	                		if(next.length > 0){
	                			next.addClass('highlight');
	                		}else{
	                			var first = self.appView.docList.children().eq(0);
                                if(first.length > 0){
                                   first.addClass('highlight');
                                }else{
                                    self.appView.updateHeaderBtn();
                                }
	                		}
	                	}else{
            				$(this).remove();
	                    }
                        self.appView.itemCollection.remove(idsArr[idx]);
                	});
                });
                if(url){
                    //delete forever, should update quota
                	App.itemHelper.updateQuota();
                }
            }
        });
    },
    
    recoverItemHandler: function(){
    	var self = this;
    	App.util.showTip(App.i18n.get('isRecoveringTip'));
    	var ids = self.getSelectedIds().join(',');
    	$.ajax({
    		type : "put",
            url : window._global.contextPath + '/recycler/'+ids+'.json',
	        success : function(data){
	        	if(data.errorItems && data.errorItems.length > 0){
	        		App.util.hideTip();
	        		self.appView.showErrorTip(data.failedItems, App.i18n.get('recoverFailedTip'));
	        	}else{
	        		App.util.hideTip(App.i18n.get('recoverSuccessTip'), 3000);
	        	}
	            App.itemHelper.removeSelectedEls(data.errorItems);
	        }
	    });
    },
    
    cutItemHandler: function(){
        var self = this;
        self.cutIds = {
            ids: self.getSelectedIds(false, true),
            parentId: self.getParentId()
        }
    },
    
    clearCutIds: function(){
        var self = this;
        self.cutIds = null;
    },
    
    pasteItemHandler: function(){
        var self = this,
        pasteTargetId = self.getPasteTargetId();
        if(!self.cutIds || self.cutIds.parentId === pasteTargetId) return;
        if(_.indexOf(self.cutIds.ids, pasteTargetId) !== -1){
            App.modalHelper.showNormalModal({
                title: 'moveFolder',
                done: function(modalBody, okBtn, cancelBtn){
                    modalBody.empty().append($('<div>', {'class': 'move-folder-tip', text: App.i18n.get('moveFolderToItSelfTip')}));
                    if(self.cutIds.ids.length === 1){
                        okBtn.hide();
                    }else{
                        okBtn.text(App.i18n.get('skip')).addClass('btn-danger').click(function(){
                            self.moveItems(pasteTargetId, _.without(self.cutIds.ids, pasteTargetId).join(','));
                        });
                    }
                }
            });
        }else{
            self.moveItems(pasteTargetId, self.cutIds.ids.join(','));
        }
    },
    
    publicItemHandler: function(){
        var self = this,
        model = self.currentSelectedItemModel;
        App.modalHelper.showNormalModal({
            title: 'public',
            button: null,
            done: function(data, modalBody, okBtn, normalModal){
            	modalBody.text(App.i18n.get('isCreaingPublicUrl'));
                $.post('/document/share/publish.json', {
                    fileId: model.get('id')
                }).done(function(data){
                    var attributes = model.get('attributes') || {};
                    attributes.publicToken = data.publicToken;
                    model.set({
                        published: true,
                        attributes: attributes
                    });
                    modalBody.empty().append($('<p>', {text: App.i18n.get('createdPublicUrlTip'), 'class': 'created-publicurl-tip'}));
                    var input = $('<input>', {'class': 'created-publicurl-inp', type: 'text', value: data.result, readonly: true}).click(function(){
                        this.select();
                    });
                    var viewLink = $('<a>', {'href': data.result, target: '_blank', text: App.i18n.get('check'), 'class': 'btn public-url-viewlink'});
                    var copyLink = $('<button>', {text: App.i18n.get('copyLink'), title: App.i18n.get('copyLink'), 'class': 'btn public-url-copylink', 'data-clipboard-text': data.result});
                    var actionBtnWrap = $('<p>', {'class': 'public-url-actionbtns'}).append(viewLink).append(copyLink);
                    modalBody.append(input).append(actionBtnWrap);
                    setTimeout(function(){
                        input.select();
                    }, 200);
                    var clip = new ZeroClipboard(copyLink[0], {
                        moviePath: "/document/js/libs/ZeroClipboard/ZeroClipboard.swf"
                    });
                    clip.on('complete', function(client, args){
                        App.util.actionTip(App.i18n.get('linkIsCopied'));
                    });
                });
            }
        });
    },
    
    unPublicItemHandler: function(){
        var self = this,
        model = self.currentSelectedItemModel;
        App.util.showTip(App.i18n.get('cancelPublish'));
        $.post('/document/share/cancelPublish.json', {
            fileId: model.get('id')
        }).done(function(e){
            App.util.hideTip();
            var contextParam = self.appView.getActionParam();
            if(contextParam.fromOwnMe){
                var attributes = model.get('attributes');
                attributes.publicToken = null;
                model.set({
                    published: false,
                    attributes: attributes
                });
            }else{
                contextParam.items.slideUp(function(){
                    $(this).remove();
                    self.appView.itemCollection.remove(model.get('id'));
                });                         
            }
        });
    },
    
    moveItems: function(parentId, fileIds){
        this.appView.moveItems(parentId, fileIds);
    },
    
    getParentId: function(){
        return this.appView.getParentId();
    },
    
    canPaste: function(target, isFolder){
        var self = this;
        if(self.cutIds){
            if($(target).is(self.docList) && self.cutIds.parentId !== self.getParentId()){
                return true;
            }else if($(target).is('.doc-item')){
                if(isFolder && self.cutIds.parentId !== self.appView.getItemModelById($(target).attr('id'))){
                    return true;
                }
            }
        }
        return false;
    },
    
    getPasteTargetId: function(){
        var self = this,
        currentItem = self.$el.data('currentItem');
        if($(currentItem).is(self.docList)){
            return self.getParentId();
        }else if($(currentItem).is('.doc-item')){
            return currentItem.data('view').model.get('id');
        }
    },
    
    getSelectedIds: function(isDeleteAction, isCutAction){
    	return App.itemHelper.getSelectedIds(isDeleteAction, isCutAction);
    },
    
    lockItemHandler: function(){
        var self = this,
        model = self.currentSelectedItemModel;
        $.post('/document/file/lock.json', {
            id: model.get('id')
        }).done(function(data){
            model.set('lock', true);
        });
    },
    
    unLockItemHandler: function(){
        var self = this,
        model = self.currentSelectedItemModel;
        $.post('/document/file/unlock.json', {
            id: model.get('id')
        }).done(function(data){
            model.set('lock', null);
        });
    },
    
    privilegeItemHandler: function(){
        var self = this,
        model = self.currentSelectedItemModel;
        App.modalHelper.showNormalModal({
            title: 'privilege',
            modalClass: 'rolemember-project-modal setprivilege-modal',
            button: null, 
            done: function(data, modalBody, okBtn, normalModal){
                self.rolePrivilegeModalBody = modalBody;
                self.privilegesCollection = new App.Collections.ItemCollection;
                self.privilegesRoleCollection = new App.Collections.ItemCollection;
                self.privilegesCollection.fetch({
                    url: App.util.contextPath + '/privilege.json?fileId=' + model.get('id'),
                    success: function(){
                        self.showRoles();
                    }
                });
                normalModal.on('hide', function(){
                   self.privilegesRoleCollection.each(function(model){
                       model.trigger('forceUpdatePrivilege');
                   }); 
                });
            }
        });
    },
    
    showRoles: function(){
        var self = this;
        self.rolePrivilegeModalBody.empty().append($('<div>', {
           'class': 'role-lst',
           text: App.i18n.get('projectRoleList')
        }).prepend($('<em>', {
           'class': 'toggle-icon-expand'
        })));
        self.privilegesCollection.each(function(model){
        	var roleModel = new App.Models.itemModel(model.get('role'));
        	roleModel.set({
               privilegeModal: true,
               privileges: model.get('privileges') ? model.get('privileges').join(',') : '',
               projectId: self.currentSelectedItemModel.get('projectId'),
               fileId: self.currentSelectedItemModel.get('id')
            });
        	self.setPrivilegeOnModel(roleModel);
            var view = new App.Views.RoleView({
                model: roleModel,
                id: App.util.getIdWithPrefix(model.get('id'))
            });
            self.privilegesRoleCollection.push(roleModel);
            self.rolePrivilegeModalBody.append(view.render().$el);
        });
    },
    
    setPrivilegeOnModel: function(model){
        var self = this,
        privileges = model.get('privileges').split(','),
        uiPrivileges = {
            readChecked: false,
            readDisabled: false,
            readInherit: false,
            writeChecked: false,
            writeDisabled: false,
            writeInherit: false,
            deleteChecked: false,
            deleteDisabled: false,
            deleteInherit: false,
            xChecked: false,
            xDisabled: false
        }
        var privilegesUsed = [];//remove i-w, i-d, i-r
        _.each(privileges, function(p){
        	p = $.trim(p);
            switch(p){
                case 'w': 
                    uiPrivileges.writeChecked = true;
                    uiPrivileges.readChecked = true;
                    uiPrivileges.readDisabled = true;
                    uiPrivileges.xChecked = true;
                    uiPrivileges.xDisabled = true;
                    privilegesUsed.push(p);
                    break;
                case 'i-w': 
                    uiPrivileges.writeChecked = true;
                    uiPrivileges.writeDisabled = true;
                    uiPrivileges.writeInherit = true;
                    uiPrivileges.readChecked = true;
                    uiPrivileges.readDisabled = true;
                    uiPrivileges.xChecked = true;
                    uiPrivileges.xDisabled = true;
                    break;
                case 'd': 
                    uiPrivileges.deleteChecked = true;
                    uiPrivileges.readChecked = true;
                    uiPrivileges.readDisabled = true;
                    uiPrivileges.xChecked = true;
                    uiPrivileges.xDisabled = true;
                    privilegesUsed.push(p);
                    break;
                case 'i-d': 
                    uiPrivileges.deleteChecked = true;
                    uiPrivileges.deleteDisabled = true;
                    uiPrivileges.deleteInherit = true;
                    uiPrivileges.readChecked = true;
                    uiPrivileges.readDisabled = true;
                    uiPrivileges.xChecked = true;
                    uiPrivileges.xDisabled = true;
                    break;
                case 'r': 
                    uiPrivileges.readChecked = true;
                    uiPrivileges.xChecked = true;
                    uiPrivileges.xDisabled = true;
                    privilegesUsed.push(p);
                    break;
                case 'i-r': 
                    uiPrivileges.readChecked = true;
                    uiPrivileges.readDisabled = true;
                    uiPrivileges.readInherit = true;
                    uiPrivileges.xChecked = true;
                    uiPrivileges.xDisabled = true;
                    break;
                case 'x': 
                    uiPrivileges.xChecked = true;
                    privilegesUsed.push(p);
                    break;
                default:
                    break;
            }
        });
        model.set({privileges: privilegesUsed.join(',')}, {silent: true});
        model.set(uiPrivileges);
    }
});
